package com.yangrui.app.server;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Component
@ServerEndpoint("/api/v1/danmu-server/{nickname}")
public class DanMuServer {

    private static Map<String , Session> clients = new ConcurrentHashMap<>();
    @OnOpen
    public void onOpen(@PathParam("nickname") String nickname , Session session){

        clients.put(nickname, session);
        log.info("{}加入聊天室", nickname);
    }

    /**
     * 当用户客户端下线时触发
     * @param nickname
     * @param session
     */
    @OnClose
    public void onClose(@PathParam("nickname") String nickname , Session session) {
        clients.remove(nickname);
        log.info("{}离开聊天室", nickname);
    }

    /**
     * 客户端发生错误时触发
     *  @param nickname ws客户标识
     *  @param e 异常实例
     *  @param session 生成的session对象
     */
    @OnError
    public void onError(@PathParam("nickname") String nickname , Session session , Throwable e) {
        log.error("{}发生错误", nickname, e);
    }

    /**
     * 服务端收到消息时触发
     * @param nickname ws客户标识
     * @param message 消息内容
     * @param session 生成的session对象
     */
    @OnMessage
    public void onMessage(@PathParam("nickname") String nickname , String message , Session session) {
        // 群发消息 对map中在线的客户端依次发送消息
        clients.keySet().forEach(client ->
                clients.get(client).getAsyncRemote().sendText(message));
    }
}
